import axios from 'axios'

const service = axios.create({
  responseType: 'arraybuffer'
})

service.interceptors.request.use(config => {
  config.headers.authentication = window.sessionStorage.getItem('tokenStr')
  return config
}, error => console.log(error))

service.interceptors.response.use(resp => {
  const headers = resp.headers
  const reg = RegExp(/application\/json/)
  if (headers['content-type'].match(reg)) {
    resp.data = unitToString(resp.data)
  } else {
    const fileDownload = require('js-file-download') // 引入的插件
    var fileName = headers['content-disposition'].split(';')[1].split('filename=')[1] // 文件名
    const contentType = headers['content-type']
    fileName = decodeURIComponent(fileName) // 格式转换，防止乱码
    fileDownload(resp.data, fileName, contentType)
  }
}, error => console.log(error))

// JSON格式的转换
function unitToString(unitArray) {
  const encodedString = String.fromCharCode.apply(null, new Uint8Array(unitArray))
  const decodedString = decodeURIComponent(escape(encodedString))
  return JSON.parse(decodedString)
}

// 定义请求（用来做下载），如果改变，直接加地址
// var base = ''
export const downloadRequest = (url, params) => {
  return service({
    method: 'GET',
    url: `${url}`,
    data: params
  })
}

export default service
